#!/usr/bin/env python

#$Id$
# -------------------------------------------------------------
#
__version__      = '$Revision$ '[11:-3]
__version_date__ = '$Date$ '[7:-3]
__author__       = 'R. Bouwens, <bouwens@ucolick.org>, D. Magee, <magee@ucolick.org>'

import pyfits
import numarray as N

def makeweight(ffin, ffout, flat, tdd, static, camera, nsamp):
    tddfile = pyfits.open(tdd)
    darkcur = tddfile[1].data
    ampglow = tddfile[2].data
    tddfile.close()
    ffo = pyfits.open(ffin)
    sci = ffo['SCI'].data
    etime = ffo['TIME'].data
    static = pyfits.getdata(static)
    bkg = ffo[0].header.get('BKGND')
    bkg *= etime
    etimez = N.where(etime==0, 1, etime)
    flatfield = pyfits.getdata(flat)    
    invflat = 1.0/N.where(flatfield==0, 1, flatfield)
    amp = ampglow*nsamp
    dark = darkcur*etimez
    if camera in [1, 2]:
        gain = 5.4
    else:
        gain = 6.5
    readnoise = 27.0
    variance = ((dark + amp)*gain + (bkg*invflat)*gain + readnoise**2)/(invflat**2 * etimez**2)
    weight = 1/(variance)
    ffo[1].header['EXTNAME'] = 'IVM'
    static = N.where(flatfield==0, 0, static)
    static = N.where(etime==0, 0, static)
    ffo[1].data = (weight*static)/(float(ffo[0].header['EXPTIME'])**2)
    ffo.writeto(ffout,clobber=True)
    ffo.close()
